package com.xxxx.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.xxxx.server.mapper.DepartmentMapper;
import com.xxxx.server.pojo.Department;
import com.xxxx.server.pojo.Position;
import com.xxxx.server.pojo.RespBean;
import com.xxxx.server.service.IDepartmentService;
import io.jsonwebtoken.lang.Collections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhoubin
 * @since 2020-10-15
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements IDepartmentService {

    @Resource
    private DepartmentMapper departmentMapper;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Override
    public List<Department> getAll() {
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        List<Department> departments = ((List<Department>) ops.get("departments"));
        if(Collections.isEmpty(departments)){
            departments = departmentMapper.getAll(-1);
            ops.set("departments",departments);
        }
        return departments;
    }

    @Override
    public int insert(Department department) {
        QueryWrapper<Department> wrapper = new QueryWrapper<>();
        wrapper.eq("name",department.getName());
        Assert.isTrue(null == departmentMapper.selectOne(wrapper),"该部门已经存在");
        department.setEnabled(true);
        department.setIsParent(false);
        departmentMapper.insert(department);
        int id = department.getId();
        Department dep = departmentMapper.selectDep(department.getParentId());
        String ParentPath = dep.getDepPath();
        String depth = ParentPath + "," + id;
        if(!dep.getIsParent()) {
            dep.setIsParent(true);
            departmentMapper.updateById(dep);
        }
        department.setDepPath(depth);
        removeCache();
        return  departmentMapper.updateById(department);
    }



    @Override
    public boolean removeById(Serializable id) {
        Department department = departmentMapper.selectById(id);
        if(department.getIsParent()){
            RespBean.error("存在子部门，不能删除");
        }
        removeCache();
        return SqlHelper.retBool(getBaseMapper().deleteById(id));
    }

    public void removeCache(){
        redisTemplate.delete("departments");
    }



}
